package misc;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ImprovedByteStream {
  private byte[] content;
  private int position = 0;
  
  public int getPosition() {
    return position;
  }

  public ImprovedByteStream(File file){
    try {
      FileInputStream inputStream = new FileInputStream(file);
      content = new byte[(int)file.length()];
      inputStream.read(content);
    }
    catch (FileNotFoundException e) {
      e.printStackTrace();
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
  
  public ImprovedByteStream(byte[] content){
    this.content = content;  
  }
  
  public int getLength(){
    return content.length;
  }
  
  public boolean searchFigure(byte[] figure){
    return searchFigure(figure, true);
  }
  
  public boolean searchFigure(byte[] figure, boolean forward){
    int initPosition = position;
    
    if(forward){
      while(position + figure.length <= content.length){
        if(isFigure(figure))
          return true;
        position++;
      }
    }
    else{
      while(position >= 0){
        if(isFigure(figure))
          return true;
        position--;
      }
    }
    position = initPosition;
    
    return false;
  }
  
  public boolean isFigure(byte[] figure){
    return isFigure(figure, position);
  }
  
  public boolean isFigure(byte[] figure, int pos){
    if(pos < 0) return false;
    
    for(int i = 0; i < figure.length; i++){
      if(pos >= content.length)
        return false;
      if(figure[i] != content[pos])
        return false;
      
      pos++;
    }
    return true;
  }
  
  public boolean read(byte[] output){
    int i = 0;
    
    while(i < output.length && position < content.length)
      output[i++] = content[position++];
    
    if(position == content.length)
      position = 0;
    
    if(i + 1 < output.length)
      return false;
    
    return true;
  }
  
  public boolean movePosition(int offset){
    int test = position + offset;
    if(test < 0 || test >= content.length)
      return false;
    
    position += offset;
    return true;
  }
  
  public int getCountToFigure(byte[] figure){
    int initPosition = position;
    if(!searchFigure(figure))
      return -1;
    
    int result = position - initPosition;
    position = initPosition;
    return result;
  }
  
  public void reset(){
    position = 0;
  }
}
